package com.shigen.demo.atguigu;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁demo
 *
 * @author shigenfu
 * @date 2022/5/22 4:42 下午
 */
public class SpinLockDemo {

  AtomicReference<Thread> atomicReference = new AtomicReference<>();

  public void myLock() {
    Thread thread = Thread.currentThread();
    System.out.println(thread.getName() + " come in.......");
    while (!atomicReference.compareAndSet(null, thread)) {

    }
  }

  public void myUnLock() {
    Thread thread = Thread.currentThread();
    atomicReference.compareAndSet(thread, null);
    System.out.println(Thread.currentThread().getName() + " myUnlock()....");
  }


  public static void main(String[] args) {
    SpinLockDemo lockDemo = new SpinLockDemo();

    new Thread(() -> {
      lockDemo.myLock();
      try {
        TimeUnit.SECONDS.sleep(5);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      lockDemo.myUnLock();
    }, "AA").start();

    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    new Thread(() -> {
      lockDemo.myLock();
      lockDemo.myUnLock();
    }, "BB").start();

  }

}
